<?php

namespace mip;

use think\Cache;
use think\Log;
use think\Request;
use think\Session;
use think\Response;

use mip\Init;

/**
 * 前台Api接口
 * @package mip
 */
class ApiBase extends Init
{

    public function _initialize() {
        parent::_initialize();

        if (!Request::instance()->isPost()) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code'=>1000, 'msg'=>'违法操作，必须POST方式请求']));
            return;
        }



        // 客户端请求的域名
        $reqDomain = input('server.SERVER_NAME') ;
        $legalSiteUrls = explode('|', config('mipInfo')['legalSiteUrl']) ;

        // 如果不是合法的网站域名 内请求，则要验证access_key
        if( array_search($reqDomain,$legalSiteUrls) === false ) {

            $header = Request::instance()->header();
            if (empty($header['terminal'])) {
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode(['code' => 1001, 'msg' => '缺少请求参数,header[terminal]']));
                return;
            }
            if (empty($header['access-key'])) {
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode(['code' => $header, 'msg' => '缺少请求参数,header[access-key]']));
                return;
            }
            $accessKey = db('AccessKey')->where('key', $header['access-key'])->where('type', $header['terminal'])->find();
            if (!$accessKey) {
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode(['code' => 1004, 'msg' => '请求参数错误,access-key or terminal not found.']));
                return;
            }
            $this->terminal = $header['terminal'];
            $this->accessKey = $header['access-key'];

        }

    }

}